package main

import (
	"github.com/iris-contrib/swagger/v12"
	"github.com/iris-contrib/swagger/v12/swaggerFiles"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/mvc"
	"github.com/kataras/iris/v12/websocket"
	"penguin/controllers"
	_ "penguin/docs"
	"penguin/penguin"
)

func Cors(ctx iris.Context) {
	ctx.Header("Access-Control-Allow-Origin", "*")
	if ctx.Request().Method == "OPTIONS" {
		ctx.Header("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,PATCH,OPTIONS")
		ctx.Header("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization")
		ctx.StatusCode(204)
		return
	}
	ctx.Next()
}

// @Title Penguin API
// @Description Penguin documents for your API
// @BasePath /v1
func main() {
	app := iris.New()
	runner := penguin.Config(app)
	mvc.Configure(app.Party("/v1/penguin"), func(application *mvc.Application) {
		application.Handle(new(controllers.PenguinController))
	})
	mvc.Configure(app.Party("/v1/user"), func(application *mvc.Application) {
		application.Handle(new(controllers.UserController))
	})
	app.Get("/swagger/{any:path}", swagger.WrapHandler(swaggerFiles.Handler))
	app.Get("/v1/ws", websocket.Handler(controllers.WebsocketServer, func(ctx iris.Context) string {
		if username := ctx.GetHeader("X-Username"); username != "" {
			return username
		}

		return websocket.DefaultIDGenerator(ctx)
	},
	))
	err := app.Run(runner)
	if err != nil {
		panic(err)
	}
}
